package com.fdmgroup.benchmarker.lib.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.fdmgroup.benchmarker.lib.common.BenchmarkReport;

public class BenchmarkReportDaoImpl extends JdbcTemplate implements
		BenchmarkReportDao {

	private static final String TABLE_NAME = "benchmark_report";

	@Override
	public void importReport(BenchmarkReport report) {
		String sql = "INSERT INTO " + TABLE_NAME + " Values(?,?,?,?,?,?)";
		update(sql,
				new Object[] { 1, report.getPerformance(),
						report.getPoolSize(), report.getSampleSize(),
						report.getTasks(), report.getDuration() });
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BenchmarkReport> getReports() {
		String sql = "SELECT * FROM " + TABLE_NAME;
		return query(sql, new BenchmarkReportRowMapper());
	}

	final static class BenchmarkReportExtractor implements ResultSetExtractor {

		@Override
		public BenchmarkReport extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			return new BenchmarkReport(rs.getInt(2), rs.getInt(3),
					rs.getInt(4), rs.getInt(5), rs.getInt(6));
		}
	}

	final static class BenchmarkReportRowMapper implements RowMapper {

		@Override
		public BenchmarkReport mapRow(ResultSet resultSet, int line)
				throws SQLException {
			BenchmarkReportExtractor extractor = new BenchmarkReportExtractor();
			return (BenchmarkReport) extractor.extractData(resultSet);
		}
	}
}
